package com.jiujia.game.sdk.base;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

/**
 * *************************************************
 * Class: JGameActivityManager
 * Author: Jiujia
 * Time: 2025/5/5 11:48
 * Description: 全局的Activity
 * *************************************************
 */
public class JGameActivityManager {
    private static volatile Activity sActivity;
    private static final Handler UI_HANDLER = new Handler(Looper.getMainLooper());

    // 私有构造
    private JGameActivityManager() {
    }

    /**
     * 初始化当前Activity（必须在主线程调用）
     */
    public static void init(Activity activity) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("Must be called on UI thread");
        }
        sActivity = activity;
    }

    /**
     * 获取当前Activity（线程安全）
     */
    public static Activity getActivity() {
        return sActivity;
    }

    /**
     * 在UI线程执行操作
     */
    public static void runOnUiThread(Runnable action) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            action.run();
        } else {
            UI_HANDLER.post(action);
        }
    }

    /**
     * 在GL线程执行操作（假设GL线程非主线程）
     */
    public static void runOnGLThread(Runnable action) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            action.run();
        } else {
            new Thread(action).start();
        }
    }

    /**
     * 退出应用
     */
    public static void finish() {
        sActivity.finish();
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}